package simple;

import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * 异步发送
 */
public class AsyncProducer {
    public static void main(String[] args) throws MQClientException, RemotingException, InterruptedException {
        DefaultMQProducer producer = new DefaultMQProducer("ASyncProducer");
        producer.setNamesrvAddr("112.124.48.207");
        producer.start();

//      CountDownLatch 计数
        CountDownLatch countDownLatch= new CountDownLatch(100);
        for (int i =0;i<100;i++){
            int index=i;
            Message message = new Message("Simple","TagA",(i+"_AsyncProducer").getBytes(StandardCharsets.UTF_8));

//          SendCallback两个回调方法：成功success，失败exception
            producer.send(message, new SendCallback() {
                @Override
                public void onSuccess(SendResult sendResult) {
                    countDownLatch.countDown();
                    System.out.println(index+"_消息发送成功"+sendResult);
                }

                @Override
                public void onException(Throwable throwable) {
                    countDownLatch.countDown();
                    System.out.println(index+"_消息发送失败"+throwable.getStackTrace());
                }
            });
        }
        countDownLatch.await(5, TimeUnit.SECONDS);
        producer.shutdown();
    }

}
